package me.monster.lab.androidrforegroundalive

import android.app.Notification
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.IBinder
import android.util.Log
import androidx.annotation.RequiresApi

/**
 * @description
 * @author: Created jiangjiwei in 2020/10/29 13:57
 */
class KeepLiveAliveService : Service() {
    companion object {
        const val SDK_INT_30 = 30
        private const val TAG = "KeepLiveAliveService"
        private const val KEY_NOTIFICATION_ID = "NOTIFICATION_ID"
        private const val KEY_START_SERVICE = "STOP_SERVICE"

        @JvmStatic
        fun start(context: Context, groupId: Int) {
            val starter = Intent(context, KeepLiveAliveService::class.java).apply {
                putExtra(KEY_NOTIFICATION_ID, groupId)
                putExtra(KEY_START_SERVICE, true)
            }
            Log.d(TAG, "notificationId $groupId try to start Service")
            context.startService(starter)
        }

        @JvmStatic
        fun stop(context: Context) {
            val starter = Intent(context, KeepLiveAliveService::class.java)
            Log.d(TAG, "try to top Service")
            context.stopService(starter)
        }
    }

    override fun onCreate() {
        super.onCreate()
        Log.d(TAG, "oncreate ");
        NotificationHelper().init(this)
    }

    var notificationId = 101
    var startNotification = true

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        intent?.apply {
            notificationId = intent.getIntExtra(KEY_NOTIFICATION_ID, 101)
            startNotification = intent.getBooleanExtra(KEY_START_SERVICE, false)
            Log.d(TAG, "notificationId $notificationId startService $startNotification ")
        }
        if (startNotification) {
            startForce()
        }
        return super.onStartCommand(intent, flags, startId)
    }

    @RequiresApi(Build.VERSION_CODES.O)
    private fun startForce() {
        Log.d(TAG, "---- start force ----")
        val notificationIntent = Intent(this, MainActivity::class.java)
        val pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0)

        val notification: Notification =
            Notification.Builder(this, NotificationHelper.notification_channel_id)
                .setContentTitle("Tittle")
                .setContentText("Content Text")
                .setSmallIcon(R.drawable.ic_launcher_background)
                .setContentIntent(pendingIntent)
                .setTicker("This is Ticker")
                .build()

        startForeground(notificationId, notification)

        Log.d(TAG, "---- end force ----")
    }

    override fun onBind(intent: Intent?): IBinder? {
        return null
    }
}